<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
      <el-form-item label="版本时间">
        <el-form-item label-width="0px">
          <el-date-picker style="width:130px" v-model="queryParams.versionStartTime" type="date" placeholder="开始时间" value-format="YYYY-MM-DD" />
        </el-form-item>
        <span class="spanStyle">至</span> 
        <el-form-item>
          <el-date-picker style="width:130px"  v-model="queryParams.versionEndTime" type="date" placeholder="结束时间" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form-item>
      <el-form-item label="上传时间">
        <el-form-item label-width="0px">
          <el-date-picker style="width:130px" v-model="queryParams.uploadStartTime" type="date" placeholder="开始时间" value-format="YYYY-MM-DD" />
        </el-form-item>
        <span class="spanStyle">至</span> 
        <el-form-item>
          <el-date-picker style="width:130px"  v-model="queryParams.uploadEndTime" type="date" placeholder="结束时间" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form-item>
      <el-form-item label="版本号" prop="versionCode">
        <el-input style="width:300px" v-model="queryParams.versionCode" placeholder="请输入版本号" clearable />
      </el-form-item>
      <el-form-item label="数据名称" prop="dataName">
        <el-input  style="width:300px" v-model="queryParams.dataName" placeholder="请输入数据名称" clearable />
      </el-form-item>
      <el-form-item label="数据类别" prop="dataType">
        <el-select v-model="queryParams.dataType" placeholder="请选择" clearable @change="chooseType"
          style="width:130px;margin-right:40px">
          <el-option v-for="item in optionData" :key="item.dictItemId" :label="item.dictItemName"
            :value="item.dictItemId">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.dataType2" placeholder="请选择" clearable style="width:130px;">
          <el-option v-for="item in optionData2" :key="item.dictItemId" :label="item.dictItemName"
            :value="item.dictItemId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据范围">
        <el-select v-model="queryParams.dataRangeCountry" placeholder="请选择" @change="chooseScope"
          style="width:130px;margin-right:10px" clearable>
          <el-option v-for="item in [{ value: 1, label: '国家级' }, { value: 2, label: '省级' }]" :key="item.value"
            :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.dataRangeProvince" placeholder="省" style="width:130px;margin-right:10px"
          @change="chooseProvince" clearable>
          <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.dataRangeCity" placeholder="市" style="width:130px;margin-right:10px"
          @change="chooseCity" clearable>
          <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.dataRangeArea" placeholder="区县" style="width:130px;" clearable>
          <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 40px;">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd">添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="Edit" :disabled="multiple" @click="handleExport">导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="primary" icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col> -->
      <div class="top-right-btn">
        <el-button style="color:#107ce5;cursor: pointer;" @click="toView">数据视图</el-button>
      </div>
    </el-row>

    <el-table v-loading="loading" ref="tableRef" :data="dataList" stripe @selection-change="handleSelectionChange"
      row-key="id">
      <el-table-column type="expand">
        <template #default="props">
          <div class="expandTable">
            <h3>更多信息</h3>
            <p>版本说明: {{ props.row.versionDesc }}（此处是版本说明，<span style="color:red">限制300字以内</span> ）</p>
            <p>数据说明: {{ props.row.dataDesc }}（此处是数据说明，<span style="color:red">限制300字以内</span> ）</p>
            <p v-if="props.row.updateDesc">更新说明: {{ props.row.dataType }}</p>
            <p>使用系统: {{ props.row.useThisSystems }}
              <el-tooltip class="box-item" content="Right Center prompts info" placement="right">
                <el-tag>系统使用说明</el-tag>
              </el-tooltip>
            </p>
            <p>数据文件:
              <template v-for="item in props.row.dataFileList">
                <u style="color:#107ce5;cursor: pointer;" @click="handleDownload(item)">{{ item.name
}}</u><br />
              </template>
            </p>
            <p>附件:
              <template v-for="item in props.row.attachmentList">
                <u style="color:#107ce5;cursor: pointer;" @click="handleDownload(item)">{{ item.name
}}</u><br />
              </template>
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
      <el-table-column label="版本时间" align="center" prop="versionTime" />
      <el-table-column label="版本号" align="center" prop="versionCode" />
      <el-table-column label="数据名称" align="center" prop="dataName" />
      <el-table-column label="数据类别" align="center" prop="dataType" />
      <el-table-column label="数据范围" align="center" prop="dataRange" />
      <el-table-column label="上传时间" align="center" prop="uploadTime" />
      <el-table-column label="上传人" align="center" prop="uploadUser" />
      <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleMore(scope.row)">更多数据</el-button>
          <el-button type="text" @click="openDetail(scope.row.versionCode)">元数据管理</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
      @pagination="getList" />

    <!-- 添加 -->
    <el-dialog v-model="open" width="800px" title="添加数据" append-to-body :show-close="false" :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
        <p class="mt15"></p>
        <el-form-item label="版本操作" prop="banben" required>
          <el-radio-group v-model="form.banben" @change="changeBanben">
            <el-radio label="保存新版本">保存新版本</el-radio>
            <template v-if="versionCodeList.length != 0">
              <el-radio label="覆盖旧版本">覆盖旧版本</el-radio>
            </template>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数据范围" prop="dataScope" required>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item prop="dataRangeCountry" label-width="0px">
                <el-select v-model="form.dataRangeCountry" placeholder="请选择" style="width:100%"
                  @change="chooseFormScope" clearable>
                  <el-option v-for="item in [{ value: 1, label: '国家级' }, { value: 2, label: '省级' }]" :key="item.value"
                    :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="dataRangeProvince" label-width="0px">
                <el-select v-model="form.dataRangeProvince" placeholder="省" style="width:100%"
                  @change="chooseFormProvince" clearable>
                  <el-option v-for="item in provinceFormData" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-select v-model="form.dataRangeCity" placeholder="市" style="width:100%" @change="chooseFormCity"
                clearable>
                <el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="form.dataRangeArea" placeholder="区县" style="width:100%" clearable>
                <el-option v-for="item in areaFormData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="数据类别" prop="type" required>
          <template style="width:100%;display: flex;justify-content: space-between;">
            <el-form-item prop="dataType" label-width="0px">
              <el-select v-model="form.dataType" placeholder="请选择数据类别" style="width:310px" clearable
                @change="chooseChildType">
                <el-option v-for="item in optionData1" :key="item.dictItemId" :label="item.dictItemName"
                  :value="item.dictItemId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="dataType2" label-width="0px">
              <el-select v-model="form.dataType2" placeholder="请选择子数据类别" style="width:310px" clearable>
                <el-option v-for="item in optionData3" :key="item.dictItemId" :label="item.dictItemName"
                  :value="item.dictItemId">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-form-item>
        <el-form-item label="数据名称" prop="dataName">
          <el-input v-model="form.dataName" placeholder="请输入数据名称" clearable />
        </el-form-item>
        <el-form-item label="数据说明" prop="dataDesc">
          <el-input v-model="form.dataDesc" type="textarea" maxlength="300" show-word-limit
            :autosize="{ minRows: 3, maxRows: 5 }" placeholder="请输入数据说明" />
        </el-form-item>
        <template v-if="form.banben != '保存新版本'">
          <el-form-item label="版本号" prop="versionCode">
            <el-select v-model="form.versionCode" placeholder="请选择版本号" style="width:100%" clearable>
              <el-option v-for="(item, index) in versionCodeList" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="版本号">
            <span>保存后自动生成</span>
          </el-form-item>
        </template>
        <el-form-item label="版本时间" prop="versionTime">
          <el-date-picker v-model="form.versionTime" type="date" placeholder="请选择版本时间" value-format="YYYY-MM-DD"
            clearable style="width:100%" />
        </el-form-item>
        <el-form-item label="版本说明" prop="versionDesc">
          <el-input v-model="form.versionDesc" type="textarea" maxlength="300" show-word-limit
            :autosize="{ minRows: 3, maxRows: 5 }" placeholder="请输入版本说明" />
        </el-form-item>
        <template v-if="form.banben != '保存新版本'">
          <el-form-item label="更新说明" prop="updateDesc">
            <el-input v-model="form.updateDesc" type="textarea" maxlength="300" show-word-limit
              :autosize="{ minRows: 3, maxRows: 5 }" placeholder="请描述版本更新的数据范围及内容，限制300字" clearable />
          </el-form-item>
        </template>
        <el-form-item label="数据文件" prop="dataFileIds" style="position:relative">
          <fileUploadData ref="dataFileRef" v-model="form.dataFileId" :fileType="fileType" @sureUploadFile="uploadFile"
            @dels="dels" :isSpatialData="isSpatialData" :name="name" :code="code" :isHasFile="isHasFile" />
          <span style="position:absolute;left:100px;top:0px;cursor: pointer;color:#107ce5" @click="handleDoc"
            v-if="(isSpatialData == 1)">字段说明</span>
        </el-form-item>
        <el-form-item label="上传附件">
          <file-upload ref="attachmentFileRef" v-model="form.attachmentId" :isShowTip="false" />
        </el-form-item>
        <el-form-item label="上传人">{{ form.user }}</el-form-item>
        <el-form-item label="上传时间">{{ form.uploadTime }}</el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" v-if="form.banben == '保存新版本'" @click="submitForm">保存</el-button>
          <el-button type="primary" v-else @click="overSave">保存</el-button>
          <!-- <el-button type="primary" @click="clearForm">清空</el-button> -->
          <el-button @click="closeForm">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 元数据信息 -->
    <el-dialog v-model="openData" width="800px" title="元数据信息" append-to-body :show-close="!isFirstOpen"
      :close-on-click-modal="!isFirstOpen" :close-on-press-escape="!isFirstOpen">
      <el-form ref="ruleFormData" :model="formData" :rules="rules" label-width="120px">
        <p class="mt15"></p>
        <el-form-item label="上传人">{{ formData.uploadUser }}</el-form-item>
        <el-form-item label="上传时间">{{ formData.uploadTime }}</el-form-item>
        <el-form-item label="数据来源" prop="uploadSource">
          <el-input v-model="formData.uploadSource" placeholder="请输入数据来源" clearable :disabled="!isFirstOpen" />
        </el-form-item>
        <el-form-item label="数据类别" prop="type">{{ formData.dataType }}</el-form-item>
        <el-form-item label="数据范围" prop="dataScope" required>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item prop="dataRangeCountry" label-width="0px">
                <el-select v-model="formData.dataRangeCountry" placeholder="请选择" style="width:100%" disabled>
                  <el-option v-for="item in [{ value: 1, label: '国家级' }, { value: 2, label: '省级' }]" :key="item.value"
                    :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="dataRangeProvince" label-width="0px">
                <el-select v-model="formData.dataRangeProvince" placeholder="省" style="width:100%" disabled>
                  <el-option v-for="item in provinceFormData1" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-select v-model="formData.dataRangeCity" placeholder="市" style="width:100%" disabled>
                <el-option v-for="item in cityFormData1" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="formData.dataRangeArea" placeholder="区县" style="width:100%" disabled>
                <el-option v-for="item in areaFormData1" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="是否空间数据" prop="isSpatialData" required>
          <el-radio-group v-model="formData.isSpatialData" disabled>
            <el-radio :label="1">空间数据</el-radio>
            <el-radio :label="0">非空间数据</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="formData.isSpatialData == '1'">
          <el-form-item label="空间数据类型" prop="spatialDataType">
            <el-radio-group v-model="formData.spatialDataType">
              <el-radio :label="1">点</el-radio>
              <el-radio :label="2">线</el-radio>
              <el-radio :label="3">面</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="tab-title">基于坐标的空间参照系</div>
          <el-form-item label="坐标系类型">{{ formData.coordinateSystemType }}</el-form-item>
          <el-form-item label="坐标系名称">{{ formData.coordinateSystemName }}</el-form-item>
          <el-form-item label="英文缩写">{{ formData.coordinateSystemEnName }}</el-form-item>
          <el-form-item label="投影信息" prop="projectionInfo">
            <el-input v-model="formData.projectionInfo" placeholder="请输入投影信息" clearable />
          </el-form-item>
        </template>
        <div class="tab-title">数据字段</div>
        <el-form-item label="字段个数" prop="fieldNum">
          <el-input v-model="formData.fieldNum" placeholder="请输入字段个数" clearable />
        </el-form-item>
        <el-form-item label="字段条目" prop="fieldEntry">
          <el-input v-model="formData.fieldEntry" placeholder="请输入字段条目" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormYuan">保存</el-button>
          <el-button v-if="!isFirstOpen" @click="openData = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="openDoc" width="800px" title="数据说明" append-to-body>
      <p class="mt15"></p>
      <p>数据类别【{{ dataType }}】应上传符合以下字段的shp文件</p>
      <el-table :data="docList" stripe>
        <el-table-column label="序号" align="center" type="index" width="80" />
        <el-table-column label="数据类别" align="center" prop="dataType" />
        <el-table-column label="是否必填" align="center" prop="isMust" />
        <el-table-column label="数据名称" align="center" prop="dataName" />
        <el-table-column label="数据说明" align="center" prop="dataDesc" width="200" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="openDoc = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- XXX数据信息（xxx版本）已存在 -->
    <el-dialog v-model="openMessage" width="500px" title="消息" append-to-body>
      <p class="mt15"></p>
      <div style="display: flex;align-items: center;">
        <el-icon :size="24" color="#E6A23C">
          <Warning />
        </el-icon>
        <span style="margin-left: 10px;line-height: 24px;">{{ tipMsg }}</span>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveData">确定</el-button>
          <el-button type="primary" @click="oldcOver">覆盖旧版本</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="basicGeography">
import { getUserId } from '@/utils/auth'
import { getProvince, getChildArea } from "@/api/system/division";
import { ElMessageBox } from 'element-plus'
import fileUploadData from '../FileUpload/index';
import { listAdministrativeArea, uploadAdministrativeArea, coverAdministrativeArea, updateAdministrativeArea, getDetail, delAdministrativeArea, dataVersionIsUseForDel, getDataTyes, getChildDataType, isExistData, dataVersionIsUse, getDataDoc, getVersionCode } from '@/api/essentialData/administrativeArea.js'
const { proxy } = getCurrentInstance();
const router = useRouter();
const dataList = ref([]);
const ids = ref([]);
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const showSearch = ref(true);
const openDoc = ref(false);
const optionData = ref([]);
const optionData1 = ref([]);
const optionData2 = ref([]);
const optionData3 = ref([]);
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]); //区、县
const provinceFormData = ref([]);//省
const cityFormData = ref([]);//市
const areaFormData = ref([]); //区、县
const provinceFormData1 = ref([]);//省
const cityFormData1 = ref([]);//市
const areaFormData1 = ref([]); //区、县
const open = ref(false);
const openData = ref(false);
const docList = ref([]);
const dataType = ref('');
const selectData = ref([]);

const isSpatialData = ref(2);
const name = ref(null);
const isHasFile = ref(0);
const fileType = ref([]);
const code = ref('');

const openMessage = ref(false);
const tipMsg = ref('');

const versionCodeList = ref([]);

const isFirstOpen = ref(true);

const coverData = ref({});

const dataRangeProvinceCheck = (rule, value, callback) => {
  if (!value && form.value.dataRangeCountry == 2) {
    callback(new Error('请选择省'))
  } else if (value == undefined && form.value.dataRangeCountry == undefined) {
    callback()
  } else {
    callback()
  }
}

const data = reactive({
  queryParams: {
    dataTypeCode: 'jjsj',
    page: 1,
    rows: 10,
    versionCode: '',
    dataName: '',
    dataType: '',
    dataRangeCountry: '',
    dataRangeProvince: '',
    dataRangeCity: '',
    versionStartTime: '',
    versionEndTime: '',
    uploadStartTime: '',
    uploadEndTime: '',
  },
  form: {
    banben: '保存新版本',
    dataScope: '1',
    type: '1',
    dataFileId: [],
    versionCode: '',
    // dataRangeCountry:'',
    // dataRangeProvince:'',
    // dataType:'',
    // dataType2:'',
    // dataName:'',
    // dataDesc:'',
    // versionTime:'',
    // versionDesc:'',
    // updateDesc:'',
    // dataFileIds:'',
  },
  formData: {
    dataScope: '1',
    type: '1',
  },
  rules: {
    dataRangeCountry: [{ required: true, message: "范围不能为空", trigger: "change" }],
    dataRangeProvince: [{ message: "省不能为空", trigger: "change", validator: dataRangeProvinceCheck }],
    dataType: [{ required: true, message: "数据类别不能为空", trigger: "change" }],
    dataType2: [{ required: true, message: "子数据类别不能为空", trigger: "change" }],
    dataName: [{ required: true, message: "数据名称不能为空", trigger: "blur" }],
    dataDesc: [{ required: true, message: "数据说明不能为空", trigger: "blur" }],
    versionCode: [{ required: true, message: "版本号不能为空", trigger: "change" }],
    versionTime: [{ required: true, message: "版本时间不能为空", trigger: "change" }],
    versionDesc: [{ required: true, message: "版本说明不能为空", trigger: "blur" }],
    updateDesc: [{ required: true, message: "更新说明不能为空", trigger: "blur" }],
    dataFileIds: [{ required: true, message: "数据文件不能为空", trigger: "blur" }],
    dataFrom: [{ required: true, message: "数据来源不能为空", trigger: "blur" }],
    uploadSource: [{ required: true, message: "数据来源不能为空", trigger: "blur" }],
    spatialDataType: [{ required: true, message: "空间数据类型不能为空", trigger: "blur" }],
    projectionInfo: [{ required: true, message: "投影信息不能为空", trigger: "blur" }],
    fieldNum: [{ required: true, message: "字段个数不能为空", trigger: "blur" }, { pattern: /^[1-9]\d*$/, message: '请输入大于0的整数！', trigger: 'change' }],
    fieldEntry: [{ required: true, message: "字段条目不能为空", trigger: "blur" }, { pattern: /^[1-9]\d*$/, message: '请输入大于0的整数！', trigger: 'change' }],
  }
})
const { queryParams, form, rules, formData } = toRefs(data);

watch(form.value, (value) => {
  // console.log(form.value.dataType2, '子数据');
  if (form.value.dataType2 && form.value.dataType2 != '') {
    optionData3.value.forEach(item => {
      if (item.dictItemId == value.dataType2) {
        isSpatialData.value = item.isSpatialData;
        name.value = item.templateFileName;
        isHasFile.value = item.isHasFile;
        code.value = item.dictItemCode;
        isSpatialData.value == 1 ? fileType.value = [] : fileType.value = ['xlsx', 'xls'];

      }
    })
  } else {
    name.value = null;
    isSpatialData.value = 2;
    isHasFile.value = 0;
    fileType.value = [];
    code.value = '';
  }
})

// 确认上传数据文件
function uploadFile(value) {
  if (value.list) {
    form.value.tempVersionCode = value.tempVersionCode;
    let arr = [];
    value.list.forEach(item => {
      arr.push(item.attachId)
    })
    form.value.dataFileIds = arr.join('');
  } else {
    form.value.tempVersionCode = null;
    form.value.dataFileIds = '';
  }
}

function dels(value) {
  form.value.tempVersionCode = null;
  form.value.dataFileIds = '';
  form.value.dataFileId = [];
}

// 去数据视图
function toView() {
  console.log(ids.value.length);
  const flag = ids.value.length == 1
  if (flag) {
    router.push({
      path: '/essentialData/dataView',
      query: {
        versionCode: selectData.value[0].versionCode,
        dataTypeCode:'jjsj'
      }
    })
  } else {
    ElMessageBox.alert('请勾选一条版本数据进行查看。', '消息提示', {
      confirmButtonText: '确认',
      type: 'warning'
    })
  }
}
// 获取版本号
function getVersionCodes() {
  getVersionCode('jjsj').then(res => {
    versionCodeList.value = res.data;
  })
}
// 获取数据类别
function getType() {
  getDataTyes('jjsj').then(res => {
    optionData1.value = res.data;
    optionData.value = [{ dictItemId: '', dictItemName: '全部' }, ...res.data];
  })
}

// 下载文件
function handleDownload(row) {
  var query = {
    attachId: row.id,
    name: row.name
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}
// 打开字段说明
function handleDoc() {
  getDataDoc(form.value.dataType2).then(res => {
    docList.value = res.data.list;
    dataType.value = res.data.name;
    openDoc.value = true;
  }).catch(_ => {
    docList.value = [];
    dataType.value = '';
    openDoc.value = false;
  })
}
// 重置数据
function reset() {
  proxy.resetForm("ruleForm");
}
//添加
function handleAdd() {
  open.value = true;
  reset();
  form.value.uploadTime = getNowFormatTime();
  form.value.uploadUser = getUserId();
  form.value.user = localStorage.getItem('userName');
  form.value.tempVersionCode = null;
  form.value.dataFileId = [];
  form.value.attachmentId = [];
}

// 判断是系统数据是否存在
function isExist() {
  const query = {
    dataRangeArea: form.value.dataRangeArea,
    dataRangeCity: form.value.dataRangeCity,
    dataRangeCountry: form.value.dataRangeCountry,
    dataRangeProvince: form.value.dataRangeProvince,
    dataTypeLevel3: form.value.dataType2,
  }
  isExistData(query).then(res => {
    open.value = false;
    if (res.data.isExist) {
      coverData.value = {};
      openMessage.value = true;
      tipMsg.value = res.data.tipMsg;
      coverData.value = form.value;
    } else {
      saveData()
    }
  })
}
function changeBanben(value) {
  form.value.versionCode = '';
  if (value == '覆盖旧版本') {
    form.value.updateDesc = '';
  }
}
// 判断后的保存
function saveData() {
  const query = {
    ...form.value,
    dataTypeLevel1Code: 'jjsj',
    dataTypeLevel2: form.value.dataType,
    dataTypeLevel3: form.value.dataType2,
  }
  uploadAdministrativeArea(query).then(res => {
    getList();
    openMessage.value = false;
    ElMessageBox.alert(`添加成功，版本号为${res.data}，请完善【元数据信息】。`, '消息', {
      confirmButtonText: '确定',
      showClose: false,
      callback: () => {
        open.value = false;
        isFirstOpen.value = true;
        handleDetail(res.data)
      },
    })
  })
}
// 覆盖旧版本
function oldcOver() {
  openMessage.value = true;
  open.value = true;
  form.value.banben = '覆盖旧版本';
}

function overSave() {
  proxy.$refs["ruleForm"].validate(valid => {
    if (valid) {
      const fileList = JSON.parse(JSON.stringify(proxy.$refs["attachmentFileRef"].fileList));
      const attachIds = [];
      for (var i = 0; i < fileList.length; i++) {
        attachIds.push(fileList[i].attachId)
      }
      form.value.attachmentIds = attachIds.join(",");
      isUse();
    }
  });

}
function coverAdministrative() {
  const querys = {
    ...form.value,
    dataTypeLevel1Code: 'jjsj',
    dataTypeLevel2: form.value.dataType,
    dataTypeLevel3: form.value.dataType2,
  }
  coverAdministrativeArea(querys).then(res => {
    getList();
    openMessage.value = false;
    ElMessageBox.alert(`覆盖成功，版本号为${res.data}，请完善【元数据信息】。`, '消息', {
      confirmButtonText: '确定',
      callback: () => {
        open.value = false;
        handleDetail(res.data)
      },
    })
  })
}
function isUse() {
  const query = {
    dataRangeArea: form.value.dataRangeArea,
    dataRangeCity: form.value.dataRangeCity,
    dataRangeCountry: form.value.dataRangeCountry,
    dataRangeProvince: form.value.dataRangeProvince,
    dataTypeLevel3: form.value.dataType2,
  }
  dataVersionIsUse({ versionCode: form.value.versionCode }).then(res => {
    const queryForm = {
      ...form.value,
      dataTypeLevel1Code: 'jjsj',
      dataTypeLevel2: form.value.dataType,
      dataTypeLevel3: form.value.dataType2,
    }
    if (res.data.isUse) {
      proxy.$modal.confirm(res.data.message, 'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(function () {
          return coverAdministrativeArea(queryForm);
        }).then((res) => {
          getList();
          ElMessageBox.alert(`覆盖成功，版本号为${res.data}，请完善【元数据信息】。`, '消息', {
            confirmButtonText: '确定',
            callback: () => {
              open.value = false;
              handleDetail(res.data)
            },
          })
        }).catch(() => { });
    } else {
      coverAdministrative();
    }
  })
}

// 保存
function submitForm() {
  proxy.$refs["ruleForm"].validate(valid => {
    if (valid) {
      const fileList = JSON.parse(JSON.stringify(proxy.$refs["attachmentFileRef"].fileList));
      const attachIds = [];
      for (var i = 0; i < fileList.length; i++) {
        attachIds.push(fileList[i].attachId)
      }
      form.value.attachmentIds = attachIds.join(",");
      isExist();
    }
  });
}

// 清空
// function clearForm () {
//     form.value.dataRangeCountry = '';
//     form.value.dataRangeProvince = '';
//     form.value.dataRangeCity = '';
//     form.value.dataRangeArea = '';
//     form.value.dataType = '';
//     form.value.dataType2 = '';
//     form.value.dataName = '';
//     form.value.dataDesc = '';
//     form.value.versionCode = '';
//     form.value.versionTime = '';
//     form.value.versionDesc = '';
//     form.value.updateDesc = '';
//     form.value.dataFileId = [];
//     form.value.dataFileIds = '';
//     form.value.attachmentId = [];
//     form.value.attachmentIds = '';
//     proxy.resetForm("ruleForm");
// }

// 关闭
function closeForm() {
  open.value = false;
}
// 更多数据
function handleMore(row) {
  proxy.$refs['tableRef'].toggleRowExpansion(row);
}

function openDetail(versionCode) {
  isFirstOpen.value = false;
  handleDetail(versionCode)
}
// 数据详情
function handleDetail(versionCode) {
  getDetail(versionCode).then(res => {
    formData.value = {
      dataScope: '1',
      type: '1',
      ...res.data,
    };
    editProvinceFormData(formData.value.dataRangeProvince, formData.value.dataRangeCity)
  })
}
// 编辑元数据
function submitFormYuan() {
  proxy.$refs["ruleFormData"].validate(valid => {
    if (valid) {
      updateAdministrativeArea({ ...formData.value }).then(res => {
        getList();
        proxy.$modal.msgSuccess("保存成功");
        openData.value = false;
      })
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/datacenter/sysDataVersion/dataExport', ids.value, `行政区划${new Date().getTime()}.xls`)
}

/** 删除按钮操作 */
function handleDelete(row) {
  dataVersionIsUseForDel({ versionCode: row.versionCode }).then(res => {
    if (res.data.isUse) {
      proxy.$modal.confirm(res.data.message, 'Warning',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(function () {
          return delAdministrativeArea(row.id);
        }).then(() => {
          getList();
          proxy.$modal.msgSuccess("删除成功");
        }).catch(() => { });
    } else {
      delAdministrativeArea(row.id).then(res => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
    }
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    dataTypeCode: 'jjsj',
    page: 1,
    rows: 10,
    versionCode: '',
    dataName: '',
    dataType: '',
    dataType2: '',
    dataRangeCountry: '',
    dataRangeProvince: '',
    dataRangeCity: '',
    dataRangeArea: '',
    versionStartTime: '',
    versionEndTime: '',
    uploadStartTime: '',
    uploadEndTime: '',
  },
    dataList.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 查询数据列表 */
function getList() {
  loading.value = true;
  listAdministrativeArea({...queryParams.value}).then(response => {
    dataList.value = response.data.list ? response.data.list : [];
    total.value = response.data.total;
    loading.value = false;
    getVersionCodes();
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selectData.value = selection;
  console.log(selectData.value, '2222');
}

//获取当前日期，格式YYYY-MM-DD
function getNowFormatTime(nowDate) {
  var char = "-";
  if (nowDate == null) {
    nowDate = new Date();
  }
  var day = nowDate.getDate();
  var month = nowDate.getMonth() + 1;//注意月份需要+1
  var year = nowDate.getFullYear();
  //补全0，并拼接
  return year + char + completeDate(month) + char + completeDate(day);
}
//获取当前时间，格式YYYY-MM-DD HH:mm:ss
// function getNowFormatTime() {
//     var nowDate = new Date();
//     var colon = ":";
//     var h = nowDate.getHours();
//     var m = nowDate.getMinutes();
//     var s = nowDate.getSeconds();
//     //补全0，并拼接
//     return getNowFormatDay(nowDate) + " " + completeDate(h) + colon + completeDate(m) + colon + completeDate(s);
// }
//补全0
function completeDate(value) {
  return value < 10 ? "0" + value : value;
}
// 获取子数据类别
function chooseType(value) {
  queryParams.value.dataType2 = '';
  if (value == '') {
    optionData2.value = [];
  } else {
    optionData1.value.forEach(item => {
      if (value == item.dictItemId) {
        getChildDataType(item.dictItemCode).then(res => {
          optionData2.value = res.data;
        })
      }
    })
  }
}

// 获取子数据类别
function chooseChildType(value) {
  form.value.dataType2 = '';
  if (value == '') {
    optionData3.value = [];
  } else {
    optionData1.value.forEach(item => {
      if (value == item.dictItemId) {
        getChildDataType(item.dictItemCode).then(res => {
          optionData3.value = res.data;
        })
      }
    })
  }
}
function chooseScope(value) {
  queryParams.value.dataRangeProvince = null;
  queryParams.value.dataRangeCity = null;
  queryParams.value.dataRangeArea = null;
}
function chooseFormScope(value) {
  form.value.dataRangeProvince = null;
  form.value.dataRangeCity = null;
  form.value.dataRangeArea = null;
  proxy.$refs['ruleForm'].validateField(['dataRangeProvince']);
}
function chooseProvince(value) {
  queryParams.value.dataRangeCity = null;
  queryParams.value.dataRangeArea = null;
  cityData.value = [];
  getChildArea(value).then(response => {
    cityData.value = response.data;
  });
}

function chooseCity(value) {
  queryParams.value.dataRangeArea = null;
  areaData.value = [];
  getChildArea(value).then((response) => {
    areaData.value = response.data;
  });
}

function chooseFormCity(value) {
  form.value.dataRangeArea = null;
  areaFormData.value = [];
  getChildArea(value).then((response) => {
    areaFormData.value = response.data;
  });
}


function chooseFormProvince(value) {
  form.value.dataRangeCity = null;
  form.value.dataRangeArea = null;
  cityFormData.value = [];
  getChildArea(value).then(response => {
    cityFormData.value = response.data;
  });
}


/** 获取省列表 */
function getProvinceData() {
  getProvince().then(response => {
    provinceData.value = response.data;
    provinceFormData.value = response.data;
    provinceFormData1.value = response.data;
  });
}

function editProvinceFormData(provinceId, cityId) {
  if (!provinceId && !cityId) {
    cityFormData1.value = [];
    areaFormData1.value = [];
  }
  if (provinceId && !cityId) {
    getChildArea(provinceId).then(response => {
      cityFormData1.value = response.data;
      areaFormData1.value = [];
    });
  }
  if (provinceId && cityId) {
    getChildArea(provinceId).then(response => {
      cityFormData1.value = response.data;
    });
    getChildArea(cityId).then(response => {
      areaFormData1.value = response.data;
    });
  }
  openData.value = true;
  proxy.resetForm("ruleFormData");
}

getType();
getProvinceData();
getList();
</script>

<style lang="scss" scoped>
.expandTable {
  padding: 5px 20px 5px 150px;

  h3 {
    font-weight: bold;
  }

  p {
    margin: 0px;
    line-height: 25px !important;
  }
}

.tab-title {
  font-size: 16px;
  font-weight: bold;
  border-left: 4px solid #0D9AFF;
  font-family: PingFangSC-Medium;
  padding-left: 10px;
  margin-bottom: 20px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0px !important;
}

.el-form--inline .el-form-item{
  margin-right: 0px!important;
}
.spanStyle{
  display: inline-block;
  width: 40px;
  text-align: center;
}
</style>
